<template>
    <el-select
        ref="scrollbarRef"
        v-model="selectId"
        filterable 
        :placeholder="placeholder" 
        :clearable="clearable" 
        remote
        reserve-keyword
        remote-show-suffix
        :remote-method="remoteMethod"
        popper-class="scroll_select" 
        @change="handleChange"
        @popup-scroll="scrollChange"
    >
        <el-option v-for="item in selectList" :key="item.id" :label="item.name" :value="item.id" />
   </el-select>
</template>
<script setup>
import { Loading } from '@element-plus/icons-vue'
import * as PersonnelApi from '@/api/system/personnel'
import { ref, reactive, watch, onMounted } from "vue"
const selectId = ref(null)
const searchName = ref('')
const total = ref(0)
const selectList = ref([])
const currentPage = ref(1)
const props = defineProps({
    placeholder: {
        type: String,
        default: '请选择'
    },
    clearable: {
        type: Boolean,
        default: false
    },
});
const $emit = defineEmits(['change', 'loadMore', 'search']);
const handleChange = (val) => {
    selectId.value = val
    let selectItem = selectList.value.find(item => item.id === val)
    $emit('change', selectItem ? selectItem : null);
}
const remoteMethod = (val) => {
    searchName.value = val
    currentPage.value = 1
    getList()
}
/** 查询角色列表 */
const getList = async () => {
    let parms = {
        name: searchName.value,
        phone: '',
        userType: 2,
        pageNo: currentPage.value,
        pageSize: 10,
    }
    try {
        const data = await PersonnelApi.getPersonnelList(parms)
        currentPage.value === 1 ? selectList.value = data.list : selectList.value.push(...data.list)
        total.value = data.total
    } finally {

    }
}

// 方法：加载更多
const loadMore = () => {
    console.log(selectList.value.length >= total.value, '没有触发？？？？');
    if (selectList.value.length >= total.value) {
        return
    }
    currentPage.value++
    getList()
}

onMounted(() => {
    const scrollContainer = scrollbarRef.value?.$el?.querySelector('.el-scrollbar__wrap')
    if (scrollContainer) {
        scrollContainer.addEventListener('scroll', handleScroll)
    }
    getList()
})
const scrollbarRef = ref()
const scrollChange = ({ scrollTop }) => {
    
    const scrollContainer = document.querySelector('.scroll_select .el-scrollbar__wrap')
    if (scrollContainer) {
        const { scrollHeight, clientHeight } = scrollContainer
        if (scrollTop + clientHeight >= scrollHeight) {
            setTimeout(() => {
                loadMore()
            }, 600)
        }
    }
}
</script>